<template>
  <section class="more-img-upload">
    <draggable v-model="fileList" element="div" :options="draggableOptions" @end="onEnd">
      <div v-for="(item,index) in fileList" :key="index" v-loading="item.loading" class="item-box">
        <imagePath style="width:100%;height:100%" :src="item.url|imageUrl" :preview-src-list="previewSrcList"></imagePath>
        <div class="tool">
          <span v-if="!disabled">
            <i class="el-icon-delete error-color" title="删除" @click="del(item,index)"></i>
          </span>
        </div>
      </div>
    </draggable>
    <div class="add">
      <el-link :disabled="disabled" :underline="false" @click="addFile">
        <i class="el-icon-plus" style="font-size:40px;"></i>
      </el-link>
      <input type="file" ref="file" @change="changeFile($event)" style="display: none;">
    </div>
    <el-select v-model="urlValueArray" multiple @change="changeInput" v-show="false">
      <el-option v-for="(item,index) in fileList" :key="index" :label="item.url" :value="item.url"></el-option>
    </el-select>
  </section>
</template>
<script>
//多图片上传，支持排序
const draggable = require("vuedraggable");
import OssFile from "@/_js/OssFile.js";
import config from "@/_config/config.js";
export default {
  props: {
    value: {},
    fileSize: {
      // 文件上传大小限制 默认2M
      default: 2097152,
      type: Number
    },
    disabled: {
      type: Boolean,
      default: false
    },
    //压缩比率0-1
    grade: {
      type: Number,
      default: 0.8
    }
  },
  computed: {
    //获取需要预览的图片地址
    previewSrcList() {
      let th = this;
      let arr = th.fileList.map(el => {
        if (el.url.includes("http")) {
          return el.url;
        } else {
          return th.$config.imageUrl + el.url;
        }
      });
      return arr;
    }
  },
  data() {
    return {
      sortable: null, //排序插件
      fileList: [], //图片列表
      urlValueArray: [],
      //拖动配置
      draggableOptions: {
        animation: 150,
        filter: ".add",
        ghostClass: "ghost-class" //拖动时的样式
        //   handle: ".more-li", //指定触发拖动元素
      }
    };
  },
  created() {
    this.setFileList();
  },
  mounted() {
    let th = this;
    //解决火狐弹出页面BUG
    document.body.ondrop = function(event) {
      event.preventDefault();
      event.stopPropagation();
    };
  },
  methods: {
    changeInput(e) {
      this.$emit("change", this.urlValueArray);
    },
    //获取到文件
    changeFile(e) {
      let th = this;
      if (e.target.files.length == 0) return;
      let file = e.target.files[0];
     
      if (file.size > th.fileSize) {
        th.$message.warning(`最大支持${Math.round(th.fileSize / 1048576)}m`);
        return;
      }
       if (file.type != "image/png" && file.type != "image/jpeg") {
        th.$message.warning("格式有误");
        return;
      }
      console.log(file);
      th.fileList.push({
        file: file,
        url: "",
        loading: true,
        loadFile(th) {
          let _this = this;
          th.$api.getTemporaryAKAndToken("web").then(res => {
            if (res.excute) {
              OssFile.uploadImage(file, res, { q: th.grade })
                .then(res => {
                  _this.url = res.path;
                  _this.loading = false;
                  //返回数据
                  th.resultData();
                })
                .catch(function(err) {
                  _this.loading = false;
                  th.$message.error("上传出错");
                });
            }
          });
        }
      });
      let data = th.fileList[th.fileList.length - 1];
      data.loadFile(th);
    },
    resultData() {
      let th = this;
      th.getValue(th.fileList);
      th.$emit("input", th.urlValueArray);
    },
    onEnd() {
      this.resultData();
    },
    getValue(list) {
      let th = this;
      let arr = [];
      for (let i = 0; i < list.length; i++) {
        let d = list[i];
        if (!d.url) continue;
        arr.push(d.url);
      }
      th.urlValueArray = arr;
    },
    del(obj, index) {
      let th = this;
      th.fileList.splice(index, 1);
      //返回数据
      th.resultData();
    },
    addFile() {
      const th=this;
      th.$refs["file"].click(); 
    },
    //设置文件列表
    setFileList() {
      let th = this;
      if (th.value.length == 0) {
        th.fileList = [];
      } else {
        if (th.fileList.length > 0) return;
        th.value.forEach(el => {
          th.fileList.push({
            url: el,
            loading: false
          });
        });
      }
    }
  },
  watch: {
    value(n, o) {
      let th = this;
      th.setFileList();
      th.urlValueArray = n;
    }
  },
  components: {
    draggable
  }
};
</script>
<style lang="scss">
.more-img-upload {
  //   display: flex;
  width: 100%;
  > div:first-child {
    display: inline-block;
    vertical-align: middle;
  }
  .item-box {
    display: inline-block;
    list-style: none;
    width: 150px;
    height: 150px;
    border-radius: 5px;
    margin-right: 10px;
    margin-bottom: 10px;
    overflow: hidden;
    position: relative;
    vertical-align: middle;
    &:hover {
      cursor: move;
    }
    .tool {
      position: absolute;
      left: 0;
      top: 0;
      display: inline-block;
      padding: 0 5px;
      background-color: rgba(#000, 0.5);
      font-size: 20px;
      i {
        cursor: pointer;
      }
    }
  }
  .ghost-class {
    box-shadow: 0 0 3px 3px #ccc;
    img {
      visibility: hidden;
    }
  }
  .add {
    width: 150px;
    height: 150px;
    font-size: 35px;
    border: 1px solid #eee;
    display: inline-block;
    line-height: 150px;
    text-align: center;
    vertical-align: middle;
    margin-right: 10px;
    margin-bottom: 10px;
    // display: flex;
    // align-items: center;
    // justify-content: center;
  }
}
</style>

